package com.htzos.base.parent.ctrl;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.htzos.admin.system.bean.SystemMenuBase;
import com.htzos.base.generate.bean.TableBean;
import com.htzos.base.generate.tool.DbManager;
import com.htzos.base.generate.tool.GenerateBeanBySingleTable;
import com.htzos.base.generate.tool.GenerateDbCodeBySingleTable;
import com.htzos.common.util.CharacterUtil;
import com.htzos.common.util.PropertiesUtil;

@Controller
@RequestMapping("/code")
public class CodeController {

	@Autowired
	DbManager dbManager;
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,
			HttpServletResponse response) {
		Connection conn = null;
		ResultSet rs = null;
		String tables = "";
		// 加载驱动程序
		try {
			// 连续数据库
			conn = jdbcTemplate.getDataSource().getConnection();
			DatabaseMetaData dmd = conn.getMetaData();
			rs = dmd.getTables(conn.getCatalog(), "root", null,new String[] { "TABLE" });
			while (rs.next()) {
				tables += rs.getString("TABLE_NAME") + ":";
			}
			if (tables.length() > 0) {
				tables = tables.substring(0, tables.length() - 1);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != rs) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
			}
			if (null != conn) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					// e.printStackTrace();
				}
			}
		}

		request.setAttribute("tables", tables);
		return new ModelAndView("/code/index");
	}
	
	@RequestMapping("/getCoulmnsList")
	public void getCoulmnsList(HttpServletRequest request,
			HttpServletResponse response) {
		String tableName=request.getParameter("tableName");
		Connection conn = null;
		ResultSet rs = null;
		String columns = "";
		String returnString="";
		// 加载驱动程序s
		try {
			// 连续数据库
			conn =  jdbcTemplate.getDataSource().getConnection();
			DatabaseMetaData dmd = conn.getMetaData();
			rs = dmd.getColumns(null, "%", tableName, "%");
			while (rs.next()) {
				columns += rs.getString("COLUMN_NAME") + ",";
			}
			if (columns.length() > 0) {
				columns = columns.substring(0, columns.length() - 1);
				
				returnString="{\"table\":\""+tableName+"\",\"supplies\":\""+columns+"\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != rs) {
				try {
					rs.close();
				} catch (SQLException e) {
					
				}
			}
			if (null != conn) {
				try {
					conn.close();
				} catch (SQLException e) {
					
				}
			}
		}

		try {
			response.getWriter().print(returnString);
		} catch (IOException e) {
			
		}

	}


	@RequestMapping("/generateBySingleTable")
	public void generateBySingleTable(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String tableName = request.getParameter("tablename");
		String packagePath = request.getParameter("packageName");
		String titleName=request.getParameter("titleName");
		
		List<String> selectedColumnList = new ArrayList<String>();
		String[] selectedColumns = request.getParameterValues(tableName + "c");
		if(selectedColumns != null) {
			selectedColumnList = Arrays.asList(selectedColumns);
		}
		
		packagePath = packagePath +"."+ tableName.split("_")[0];
		String saveJAVAPath =PropertiesUtil.PROJECTSRC;
		String saveJSPPath =PropertiesUtil.PROJECTWEB;
		String[] dirArray = packagePath.split("\\.");
		File file = null;
		
		file=new File(saveJAVAPath);
		if(!file.exists()){    
			file.mkdir();
		}
		
		for (int i = 0; i < dirArray.length; i++) {
			file = new File(saveJAVAPath + dirArray[i]);
			if(!file.exists()){    
				file.mkdir();
			}
			saveJAVAPath += dirArray[i] + "/";
		}
		// 建立包类下的子目录
		file = new File(saveJAVAPath + "bean");
		if(!file.exists()){    
			file.mkdir();
		}
		file = new File(saveJAVAPath + "dao");
		if(!file.exists()){    
			file.mkdir();
		}
		file = new File(saveJAVAPath + "service");
		if(!file.exists()){    
			file.mkdir();
		}
		file = new File(saveJAVAPath + "controller");
		if(!file.exists()){    
			file.mkdir();
		}
		
		saveJSPPath +=  tableName.split("_")[0]+"/";
		file = new File(saveJSPPath);
		if(!file.exists()){    
			file.mkdir();
		}

		Map<String, TableBean> columns;
		String pkName;
		try {
			// 生成Bean文件
			columns = dbManager.getTableInfo(tableName);
			
			pkName=dbManager.getPkName(tableName);
			
			GenerateBeanBySingleTable generateBeanBySingleTable = new GenerateBeanBySingleTable();
			generateBeanBySingleTable.generateBeanFile(packagePath, tableName,pkName,
					columns, saveJAVAPath + "bean/");
			// 生成数据库操作文件
			GenerateDbCodeBySingleTable generateDbCodeBySingleTable = new GenerateDbCodeBySingleTable();
			generateDbCodeBySingleTable.generateDbJAVAFile(packagePath,tableName,pkName, columns, saveJAVAPath, selectedColumnList);
			// 生成JSP页面文件
			generateDbCodeBySingleTable.generateDbJSPFile(packagePath,tableName,titleName,pkName,columns, saveJSPPath, selectedColumnList);
			
			//将刚生成的插入菜单表
			SystemMenuBase menu=new SystemMenuBase();
			menu.setParentId(0);
			menu.setMenuName(titleName+"管理");
			String beanName=CharacterUtil.returnBeanName(tableName);
			String attiName=CharacterUtil.firstLowCase(beanName);
			menu.setMenuUrl("../"+attiName+"/list");
			menu.setIconImage("fa fa-close");
			menu.setOrderBy(0);
			menu.setAddUrl("../"+attiName+"/addPage;../"+attiName+"/insert");
			menu.setDeleteUrl("../"+attiName+"/delete");
			menu.setUpdateUrl("../"+attiName+"/updatePage;../"+attiName+"/update");
			menu.setSelectUrl("../"+attiName+"/list;../"+attiName+"/detail");
			dbManager.insertMenu(menu);
			
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().print("生成结束");
		} catch (SQLException e) {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().print("生成异常:"+e.getMessage());
		} catch (IOException e) {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().print("生成异常:"+e.getMessage());
		} catch (Exception e) {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.getWriter().print("生成异常:"+e.getMessage());
		}
	}

}
